package com.kotlin.demo.net

import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit

object OkHttpUtil {
    const val TAG = "OkHttpUtil"
    private const val CONNECT_TIMEOUT = 100
    private const val READ_TIMEOUT = 100
    private const val WRITE_TIMEOUT = 100

    // 后台数据接口基础路径
    const val BASE_URL = "http://saas.jetinno.com/api"
    private val client: OkHttpClient = OkHttpClient.Builder()
        .readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS) // 设置读取超时时间
        .writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS) // 设置写的超时时间
        .connectTimeout(CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS) // 设置连接超时时间
        .addInterceptor(HttpLogInterceptor())
        .build()
    val JSON = MediaType.parse("application/json; charset=utf-8")

    //post请求，携带参数
    fun post(url: String, requestBody: RequestBody, httpCallBack: HttpCallBack?) {
//        RequestBody body = RequestBody.create(JSON, json);
        val request = Request.Builder()
            .url(url)
            .addHeader("API-Key", "1475F22EF5ECE7BA19AF85273763F9C6")
            .post(requestBody)
            .build()
        val call = client.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                println("$TAG:onFailure: ")
                httpCallBack!!.callBack("")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful && response.body() != null) {
                    val res = response.body()!!.string()
                    httpCallBack?.callBack(res)
                } else {
                    if (response.body() != null) {
                        httpCallBack!!.callBack(response.body()!!.string())
                    }
                    throw IOException("Unexpected code $response")
                }
            }
        })
    }

    //get请求。不带参数
    operator fun get(url: String, httpCallBack: HttpCallBack?) {
        val request = Request.Builder()
            .url(url)
            .get()
            .build()
        //同步请求返回的是response对象
        val call = client.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                println("$TAG:onFailure: ")
                httpCallBack!!.callBack("")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                if ( response.isSuccessful && response.body() != null) {
                    val res = response.body()!!.string()
                    httpCallBack?.callBack(res)
                } else {
                    httpCallBack!!.callBack("")
                    throw IOException("Unexpected code $response")
                }
            }
        })
    }

    interface HttpCallBack {
        fun callBack(response: String?)
    }
}